package com.sherry.servlet;

import com.alibaba.fastjson.JSONObject;
import com.sherry.model.User;
import com.sherry.service.IUserService;
import com.sherry.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//@WebServlet("/LoginServlet")
@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    // 处理post请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("接收到前端POST请求");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");


//        一般只有接收参数这里需要改
//       6. 接收前端发的请求的参数,这里的字段名一定要和前端请求匹配上
        String account= request.getParameter("userNameLogin");
        String pwd= request.getParameter("userPwdLogin");
//        这里输出的数据来自前端请求里携带的参数
        System.out.println("servlet层 account= "+account+ " pwd= "+pwd);


//        7.获取业务层对象，并获取其方法，及传递前端参数给业务层（service层）
//        对象类型以接口类型定义，new的类型是非抽象impl实现类
        IUserService userService=new UserServiceImpl();
        User user=userService.login(account,pwd);
//        user拿到Service业务层里的login方法返回的userDao.getUser(acc,pwd)数据


        String msg="";

        boolean flag=false;
        if(user!=null){
            flag=true;
            msg="操作成功";
        }
        else {
            msg="操作失败";
        }

//        处理数据
        JSONObject data=new JSONObject();
        data.put("user",user);
        data.put("flag",flag);
        data.put("msg",msg);

//对象数据变字符串
        String dataStr=data.toJSONString();


        //响应数据给前端（前端检查工具里的控制台可看输出）
        PrintWriter write = response.getWriter();
        write.write(dataStr);
        write.flush();
    }

    // 处理get请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("接收到前端GET请求");
        doPost(request,response);
    }
}